import { Request, Response, NextFunction, } from 'express';
import NodeAuth from 'node-auth0';
import Db from './../db';
import { generateToken } from './../utils';
// import HttpException from '../exceptions/HttpException';
// import { UNPROCESSABLE_ENTITY, UNAUTHORIZED } from 'http-status-codes';

const nodeAuth = new NodeAuth();

export const register = async (req: Request, res: Response, next: NextFunction) => {
  let { username, password } = req.body;
  console.log(username, password, '获取的数据')
  try {
    // 查找是否已经创建改用户
    const isExist = await Db.query(`select count(*) as count from account where username = "${username}"`);
    if (isExist && isExist[0].count) {
      res.json({
        code: 1,
        message: '该用户已经存在,不能重复创建',
      });
    }
    const newPassword = nodeAuth.makePassword(password);
    // 插入数据
    const { affectedRows } = await Db.query(`insert into account(username, password) values(?, ?)`, [username, newPassword]);
    if (affectedRows) {
      // 返回数据
      res.json({
        code: 0,
        message: '创建成功',
      });
    } else {
      res.json({
        code: 1,
        message: '创建失败',
      });
    }
  } catch (error) {
    next(error);
  };
}


// 用户登录
export const login = async (req: Request, res: Response, next: NextFunction) => {
  try {
    const { username, password } = req.body;
    console.log('接收的参数',username, password);
    const userInfo = await Db.query(`select id, username, password from account where username = ? limit 1`, [username]);
    if (userInfo && userInfo.length) {
      if (nodeAuth.checkPassword(password, userInfo[0].password)) {
        const token = await generateToken(userInfo[0].id);
        console.log(userInfo[0].id, '当前id')
        res.json({
          code: 0,
          message: '登录成功',
          token,
          username: userInfo[0].username,
        })
      } else {
        res.json({
          code: 1,
          message: '用户名或密码错误',
        })
      }
    } else {
      res.json({
        code: 1,
        message: '用户名或密码错误',
      })
    }
  } catch (error) {
    next(error);
  }
}

// 用户列表
export const userList = async (req: any, res: Response, next: NextFunction) => {
  try {
    console.log(req.userId, '===')
    res.json({
      code: 0,
      message: '成功',
    })
  } catch (error) {
    next(error);
  }
}
// 上传文件
export const uploadAvatar = async (req: Request, res: Response, next: NextFunction) => {
  try {
    // const { userId } = req.body;
    let avatar = `${req.protocol}://${req.headers.host}/uploads/${req.file.filename}`;
    // await User.updateOne({ _id: userId }, { avatar });
    //处理上传的文件，然后更新数据库，更新此用户对应的avatar字段。然后返回真实的图片路径
    res.json({
      success: true,
      data: avatar
    });
  } catch (error) {
    next(error);
  }
}